const app = getApp();
const { getOpenID } = require('../../utils/ws/wsxcx-opendata-sdk');
const WxNotificationCenter = require('../../utils/WxNotificationCenter/WxNotificationCenter.js');
const includes = (arr = [], item = '') => arr.indexOf(item) >= 0;

Component({
  properties: {
    toolType: {
      type: String,
      value: '',
    },

    needLotteryPath: {
      type: Boolean,
      value: false,
    },

    needLotteryResult: {
      type: Boolean,
      value: false,
    },

    bottom: {
      type: Number,
      value: 0, 
    },

  },

  data: {
    entryType: 'button',
    activity: {},
    lotteryPath: '',
    basePath: '/cm_lottery/pages/',
  },

  externalClasses: ['custom-lottery-btn', 'icon', 'icon-guanbi2'],

  attached() {
    this.getLotteryInfo();
    this.onLotteryResult = this.onLotteryResult.bind(this);
    this.data.needLotteryResult && WxNotificationCenter.addOnceNotification('lotteryResult', this.onLotteryResult);
  },

  methods: {
    getLotteryInfo() {
      let { needLotteryPath, basePath, toolType } = this.data;
      toolType === 'cardsCollecting' && (basePath = '/cm_cards_collecting/pages/');  // 集卡分包路径
      let url = getCurrentPages().pop().route;
      this.doRequest(toolType).then(data => {
        let activity = data.find(item => {
          return item.page_link === url;
        });
        let { entry_type: entryType, lottory_type: lotteryType = '', id } = activity || {};
        let lotteryPath =
          toolType === 'cardsCollecting'
            ? `${basePath}index/index?id=${id}`
            : `${basePath}index/index?type=${lotteryType}&id=${id}`;

        entryType && this.setData({
          showModal: includes(entryType, 'modal'),
          showButton: includes(entryType, 'button'),
          showFloating: includes(entryType, 'floating'),
          activity,
          entryType,
          lotteryPath,
        });
        needLotteryPath && this.triggerEvent('getLotteryInfo', activity);
      });
    },

    doRequest(toolType) {
      return new Promise(resolve => {
        getOpenID({ mode: 1 }).then(() => {
          app.util.request({
            url: toolType === 'cardsCollecting' ? 'wxapp/home/cards_collecting' : 'wxapp/home/lottery',
            data: {},
            method: 'get',
            cachetime: 0,
            success: res => {
              res.data.errno === 0 && Array.isArray(res.data.data) && resolve(res.data.data);
            },
          });
        });
      });
    },

    gotoLottery() {
        app.util.navigateTo(this.data.lotteryPath);
    },

    closeModal() {
      this.setData({ showModal: false });
    },

    onLotteryResult(info) {
      info && this.triggerEvent('getLotteryResult', info);
    },
  },
});